/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org

http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package com.happybluefin.tapburstfree.window;

import java.util.List;

import net.cavas.show.MainLoadCavasManager;

import org.cocos2dx.lib.Cocos2dxActivity;

import com.adsmogo.adview.AdsMogoLayout;
import com.adsmogo.controller.listener.AdsMogoListener;
import com.adsmogo.util.AdsMogoTargeting;

import com.happybluefin.tapburstfree.R;
import com.happybluefin.tapburstfree.message.Define;
import com.happybluefin.tapburstfree.application.TapBurstFreeApplication;
import com.happybluefin.tapburstfree.common.data.RomData;
import com.happybluefin.tapburstfree.common.jni.LanguageJni;
import com.happybluefin.tapburstfree.common.scoreloop.Scoreloop;
import com.happybluefin.tapburstfree.common.scoreloop.ScoreloopCallback;
import com.happybluefin.tapburstfree.common.sinaweibo.SinaWeibo;
import com.happybluefin.tapburstfree.common.sinaweibo.SinaWeiboCallback;
import com.kuguo.ad.KuguoAdsManager;
import com.scoreloop.client.android.ui.LeaderboardsScreenActivity;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;
import com.BXUTbgRJDO.LurLPZZOxI119539.Airpush;

import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.Toast;
import android.view.Gravity;
import android.view.ViewGroup;

public class TapBurstFreeWindow extends Cocos2dxActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate() start");

        IntentFilter filter = new IntentFilter();
        filter.addAction(Define.Action.ACTION);
        registerReceiver(mReceiver, filter);

        // add advertisement layout
        if (TapBurstFreeApplication.mIsAdBannerEnable == 1) {
            //adsmogo interface
            mAdsMogoLayout = new AdsMogoLayout(this,
                                               RomData.ADS_MOGO_APP_ID,
                                               AdsMogoTargeting.GETINFO_PHONE_BANNER_AD);

            mAdsMogoLayout.setAdsMogoListener(new AdsMogoListener() {
                @Override
                public void onClickAd(String adName) {
                    Log.d(TAG, "onClickAd() adName: " + adName);
                }

                @Override
                public void onCloseAd() {
                }

                @Override
                public void onCloseMogoDialog() {
                }

                @Override
                public void onFailedReceiveAd() {
                }

                @Override
                public void onRealClickAd() {
                }

                @Override
                public void onReceiveAd(ViewGroup adView, String adName) {
                    Log.d(TAG, "onReceiveAd() adName: " + adName);
                }

                @Override
                public void onRequestAd(String adName) {
                    Log.d(TAG, "onRequestAd() adName: " + adName);
                }
            });
//            framelayout.addView(mAdsMogoLayout, params);
            FrameLayout framelayout = (FrameLayout) this.getWindow().getDecorView();
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT,
                    FrameLayout.LayoutParams.WRAP_CONTENT);
            params.topMargin = 0;
            params.gravity = Gravity.TOP;
            framelayout.addView(mAdsMogoLayout, params);
        }

        // umeng interface
        // auto update interface
        UmengUpdateAgent.update(this);
        // user event analytics
        MobclickAgent.onError(this);
        MobclickAgent.updateOnlineConfig(this);

        if (TapBurstFreeApplication.mIsAdPushEnable == 1) {
            if (LanguageJni.isChinese()) {
                // kuguo interface
                KuguoAdsManager.getInstance().receivePushMessage(this, true);
            }
            else {
                // airpush interface
                mAirpush = new Airpush(this);
                mAirpush.startSmartWallAd();
                mAirpush.startPushNotification(false);
                mAirpush.startIconAd();
            }
        }

        Log.d(TAG, "onCreate() end");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy() start");

        if (TapBurstFreeApplication.mIsAdBannerEnable == 1) {
            AdsMogoLayout.clear();
            mAdsMogoLayout.clearThread();
        }

        if (TapBurstFreeApplication.mIsAdPushEnable == 1) {
            KuguoAdsManager.getInstance().recycle(this);
        }

        unregisterReceiver(mReceiver);

        Log.d(TAG, "onDestroy() end");
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "onPause() start");

        super.onPause();

        MobclickAgent.onPause(this);

        Log.d(TAG, "onPause() end");
    }

    @Override
    protected void onResume() {
        Log.d(TAG, "onResume() start");

        super.onResume();

        MobclickAgent.onResume(this);

        Log.d(TAG, "onResume() end");
    }

    static {
        System.loadLibrary("game");
    }

    private void _showLeaderboard(String boardName) {
        Log.d(TAG, "_showLeaderboard() start");

        Intent intent = new Intent(TapBurstFreeWindow.this, LeaderboardsScreenActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        TapBurstFreeWindow.this.startActivity(intent);

        Log.d(TAG, "_showLeaderboard() end");
    }

    private void _reportScore(String boardName, int score) {
        Log.d(TAG, "_reportScore() start");

        Scoreloop scoreloop = new Scoreloop(new ScoreloopCallback() {
            @Override
            public void submitResult(boolean result) {
                if (result == false) {
                    Toast.makeText(TapBurstFreeWindow.this, getString(R.string.submit_failed), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void getLeaderboardResult(boolean result, List<String> list) {
                // TODO Auto-generated method stub
            }

            @Override
            public void getRankResult(boolean result, int rank, int count) {
                // TODO Auto-generated method stub
            }
        });

        scoreloop.submitScore(boardName, score);

        Log.d(TAG, "_reportScore() end");
    }

    private void _sinaWeiboShare(final String text) {
        Log.d(TAG, "_sinaWeiboShare() start");

        SinaWeibo weibo = new SinaWeibo(this, new SinaWeiboCallback() {
            @Override
            public void shareResult(boolean result) {
                // TODO Auto-generated method stub
            }

            @Override
            public void cancel() {
                // TODO Auto-generated method stub
            }
        });
        weibo.share(text);

        Log.d(TAG, "_sinaWeiboShare() end");
    }

    private void _tencentWeiboShare(final String text) {
        Log.d(TAG, "_tencentWeiboShare() start");

        try {
            Intent intent = new Intent(TapBurstFreeWindow.this, TencentWeiboWindow.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("TEXT", text);
            TapBurstFreeWindow.this.startActivity(intent);
        }
        catch (NullPointerException e) {
            e.printStackTrace();
        }
        catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }

        Log.d(TAG, "_tencentWeiboShare() end");
    }

    private void _webBrowser(final String url) {
        Log.d(TAG, "_webBrowser() start");

        try {
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            TapBurstFreeWindow.this.startActivity(intent);
        }
        catch (NullPointerException e) {
            e.printStackTrace();
        }
        catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }

        Log.d(TAG, "_webBrowser() end");
    }

    private void _openAdsMogoOffer() {
        Log.d(TAG, "_openAdsMogoOffer() start");

        MainLoadCavasManager offerManager = new MainLoadCavasManager(this);
        offerManager.setTitleTheme(MainLoadCavasManager.OFFER_TITLE_THEME_BLUE);
        offerManager.setAdMogoKey(RomData.ADS_MOGO_APP_ID);
        offerManager.openOffer();

        Log.d(TAG, "_openAdsMogoOffer() end");
    }
    
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "BroadcastReceiver::onReceive() start");

            if (intent != null) {
                Bundle bundle = intent.getExtras();

                int type = bundle.getInt("TYPE");
                String boardName = bundle.getString("BOARDNAME");
                int score = bundle.getInt("SCORE");
                String text = bundle.getString("TEXT");
                String url = bundle.getString("URL");
                switch (type) {
                case Define.MessageID.SHOW_LEADERBOARD:
                    _showLeaderboard(boardName);
                    break;

                case Define.MessageID.REPORT_SCORE:
                    _reportScore(boardName, score);
                    break;

                case Define.MessageID.SINA_WEIBO_SHARE:
                    _sinaWeiboShare(text);
                    break;

                case Define.MessageID.TENCENT_WEIBO_SHARE:
                    _tencentWeiboShare(text);
                    break;

                case Define.MessageID.WEB_BROWSER:
                    _webBrowser(url);
                    break;

                case Define.MessageID.OPEN_ADS_MOGO_OFFER:
                    _openAdsMogoOffer();
                    break;
                    
                default:
                    break;
                }
            }

            Log.d(TAG, "BroadcastReceiver::onReceive() end");
        }
    };

    private AdsMogoLayout mAdsMogoLayout = null;

    private Airpush mAirpush = null;

//    private static final String ADS_MOGO_APP_ID = "417f1969c2b043efbe62a75a7cfe35df";

    private static final String TAG = "TapBurstFreeWindow";
}
